package org.jac.hibernate;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by JAC.
 * Date: 14-3-25
 * Time: 下午4:44
 */
public final class HibernateUtil{
    private static SessionFactory sessionFactory;
    //禁止HibernateUtil实例化
    private HibernateUtil(){}
    static {
        Configuration configuration = new Configuration().configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    public static Session getSession(){
        return sessionFactory.openSession();
    }

    /**
     * 根据id获取单个对象
     * @param entityClass
     * @param id
     * @return
     */
    public static Object getEntityById(Class entityClass,Serializable id){
        Object entity = null;
        Session session = null;
        try {
            session = HibernateUtil.getSession();
            entity = session.get(entityClass,id);

        } finally {
            if(session != null){
                session.close();
            }
        }
        return entity;
    }

    /**
     *
     * @param hql
     * @param params
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T>List<T> query(String hql,Object...params){
        List<T> resultList = new ArrayList<T>();
        Query query = HibernateUtil.getSession().createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setString(i,params[i].toString());
        }

        List list = query.list();
        for (Object o : query.list()) {
            resultList.add((T) o);
        }
        return query.list();
    }

    /**
     *
     * @param hql
     * @param pageIndex
     * @param pageMax
     * @param params
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T>List<T> queryToPaging(String hql,int pageIndex,int pageMax,Object...params){
        List<T> resultList = new ArrayList<T>();
        Query query = HibernateUtil.getSession().createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setString(i,params[i].toString());
        }
        query.setFirstResult((pageIndex-1)*pageMax);
        query.setMaxResults(pageIndex*pageMax);
        List list = query.list();
        for (Object o : query.list()) {
            resultList.add((T) o);
        }
        return query.list();
    }

    /**
     * 增加保存多个或一个对象
     * @param entitys 保存对象集合
     */
    public static void add(Object...entitys){
        Session session = null;
        Transaction ta = null;
        try {
            session = HibernateUtil.getSession();
            ta = session.beginTransaction();
            for (int i = 0; i < entitys.length; i++){
                session.save(entitys[i]);
            }
            ta.commit();
        } finally {
            if(session != null){
                session.close();
            }
        }
    }

    /**
     * 更新保存多个或一个对象
     * @param entitys 保存对象集合
     */
    public static void update(Object...entitys){
        Session session = null;
        Transaction ta = null;
        try {
            session = HibernateUtil.getSession();
            ta = session.beginTransaction();
            for (int i = 0; i < entitys.length; i++){
                session.update(entitys[i]);
            }
            ta.commit();
        } finally {
            if(session != null){
                session.close();
            }
        }
    }

    /**
     * 删除多个或一个对象
     * @param entitys 删除对象集合
     */
    public static void delete(Object...entitys){
        Session session = null;
        Transaction ta = null;
        try {
            session = HibernateUtil.getSession();
            ta = session.beginTransaction();
            for (int i = 0; i < entitys.length; i++){
                session.delete(entitys[i]);
            }
            ta.commit();
        } finally {
            if(session != null){
                session.close();
            }
        }
    }
}
